package lg.minecraft.plugin.entityclear.util;

import lg.minecraft.plugin.entityclear.component.EntityFilter;
import lg.minecraft.plugin.entityclear.component.EntityRemover;
import lg.minecraft.plugin.entityclear.component.WorldFilter;
import lg.minecraft.plugin.entityclear.parser.ParserContext;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.EntityType;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * 组件工具类，提供默认的组件实现
 *
 * @author langle__
 * @version 1.0
 */
public class ComponentUtil {

    public static @NotNull EntityRemover createDefaultEntityRemover(@NotNull ParserContext context) {
        return entity -> {
            try {
                entity.remove();
                return true;
            } catch (Exception e) {
                return false;
            }
        };
    }

    public static @NotNull WorldFilter createWhiteListWorldFilter(@NotNull ParserContext context) {
        ConfigurationSection config = context.getConfig();
        if (config == null) {
            return world -> false;
        }
        final List<String> list = config.getStringList("list");
        return world -> list.contains(world.getName());
    }

    public static @NotNull WorldFilter createBlackListWorldFilter(@NotNull ParserContext context) {
        ConfigurationSection config = context.getConfig();
        if (config == null) {
            return world -> true;
        }
        final List<String> list = config.getStringList("list");
        return world -> !list.contains(world.getName());
    }

    public static @NotNull EntityFilter createWhiteListEntityFilter(@NotNull ParserContext context) {
        ConfigurationSection config = context.getConfig();
        if (config == null) {
            return world -> false;
        }
        final List<EntityType> list = new ArrayList<>();
        for (String s : config.getStringList("list")) {
            EntityType entityType = EntityTypeUtil.getEntityType(s);
            if (entityType != null) {
                list.add(entityType);
            } else {
                context.warning("无法识别的实体类型: {0}", s);
            }
        }
        return entity -> list.contains(entity.getType());
    }

    public static @NotNull EntityFilter createBlackListEntityFilter(@NotNull ParserContext context) {
        ConfigurationSection config = context.getConfig();
        if (config == null) {
            return world -> true;
        }
        final List<EntityType> list = new ArrayList<>();
        for (String s : config.getStringList("list")) {
            EntityType entityType = EntityTypeUtil.getEntityType(s);
            if (entityType != null) {
                list.add(entityType);
            } else {
                context.warning("无法识别的实体类型: {0}", s);
            }
        }
        return entity -> !list.contains(entity.getType());
    }

}
